// pages/personpage/personpage.js
let md5 = require("../../utils/md5.js")
let axios = require("../../utils/util.js")
const app = getApp()
const recorderManager = wx.getRecorderManager() //录音
const innerAudioContext = wx.createInnerAudioContext() //播放语音
Page({

  /**
   * 页面的初始数据
   */
  data: {
    minute: 0,
    second: 0,
    millisecond: 0,
    timecount: '00:00',
    init: null,

    open_RecordingPopup: false,
    personInfo: {
      level: '',
      charmLevel: '',
    }, //所有个人主页信息
    changeShow: true,
    img_level: "https://xunyinjiaoyou.oss-cn-qingdao.aliyuncs.com/static/level3/",
    img_charm: "https://xunyinjiaoyou.oss-cn-qingdao.aliyuncs.com/static/charm3/",
    memberId: '', //查看人id
    imgList: [], //预览放大背景图
    recordList: [], //我的动态
    pic: [], //动态图片
    productInfo: {}, //上传图片
    concent: '', //个性签名
    // most_list:'',//签名
    ismy_home: false,
    is_statys: false,
    dianjiluzhi: true, //点击录制
    luzhizhong: false, //录制中
    shiting: false, //试听
    shiting_2: true,
    bofang_zhanting: false, //暂停
    Start_top: '点击下方录制按钮，开始录制声音',
    Start_bottom: '开始录音',
    tempFilePath: '', //录音文件流
  },
  //去聊天
  tomessage_(data) {
    let perfect_number = data.currentTarget.dataset.perfect_number
    let datas = JSON.stringify(perfect_number)
    wx.navigateTo({
      url: '/pages/messageInfo/messageInfo?perfect_number=' + encodeURIComponent(datas),
    })
  },
  //语音播放
  start(data) {
    let e = data.currentTarget.dataset.url
    console.log(e);
    this.setData({
      is_statys: !this.data.is_statys
    })
    if (this.data.is_statys) {
      innerAudioContext.src = e;
      innerAudioContext.play(); //开始播放 
    } else {
      console.log("暂停");
      innerAudioContext.pause()
    }
  },
  //失去焦点时获取里面评论内容
  bindTextAreaBlur: function (e) {
    // console.log(e.detail.value)
    this.setData({
      concent: e.detail.value,
    })
  },
  //顶部跳转去房间
  // toroom_(){
  //  wx.navigateTo({
  //     url: '/pages/room/room?roomId=' + this.data.personInfo.inRoomId,
  //   })
  // },
  //点击我显示底部弹出框
  clickme(data) {
    let most_list = data.currentTarget.dataset.item
    console.log(most_list);
    this.setData({
      concent: most_list
    })
    this.showModal();
  },
  baochun() {
    console.log(this.data.concent);
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let arys = {
      sex: '',
      originSign: this.data.concent,
      birthday: '',
      invitedId: '',
      nickName: '',
      headPic: '',
      userId: this.data.personInfo.userId.toString(),
      time: timestamp,
      token: app.globalData.userToken,
    };
    console.log(arys);
    let _token = axios.encryption(arys);
    let params = {
      sex: '',
      originSign: this.data.concent,
      birthday: '',
      invitedId: '',
      nickName: '',
      headPic: '',
      userId: this.data.personInfo.userId.toString(),
      time: timestamp,
      token: app.globalData.userToken,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/user/editUserProfile",
      data: params
    }).then((res) => {
      console.log(res);
      if (res.data.status == 0) {
        wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000 //持续的时间
        })
        this.homeIndex()
        this.hideModal()
      }
    })
  },
  //添加关系卡
  addcard() {
    console.log('添加');
    let that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original'], //原图
      sourceType: ['album', 'camera'], //支持选取图片
      success(res) {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths[0];
        that.addcar_ad(tempFilePaths)
        // that.addcar_ad(res.tempFilePaths)

      }
    })
  },
  //添加关系卡
  addcar_ad(cardfile) {
    console.log(cardfile);
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let arys = {
      userId: this.data.personInfo.userId.toString(),
      cardfile: cardfile,
      time: timestamp,
      token: app.globalData.userToken,
    };
    console.log(arys);
    let _token = axios.encryption(arys);
    let params = {
      userId: this.data.personInfo.userId.toString(),
      cardfile: cardfile,
      time: timestamp,
      token: app.globalData.userToken,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/user/addcard",
      data: params
    }).then((res) => {
      console.log(res);
      if (res.data.status == 0) {
        wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000 //持续的时间
        })
        // this.homeIndex()
      } else {
        wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000 //持续的时间
        })
      }
    })
  },
  //删除关系卡
  deletecard(data) {
    let cardid = data.currentTarget.dataset.cardid
    console.log(cardid);
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let arys = {
      userId: this.data.personInfo.userId,
      cardid: cardid,
      time: timestamp,
      token: app.globalData.userToken,
    };
    let _token = axios.encryption(arys);
    let params = {
      userId: this.data.personInfo.userId,
      cardid: cardid,
      time: timestamp,
      token: app.globalData.userToken,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/user/delcard",
      data: params
    }).then((res) => {
      // console.log(res);
      if (res.data.status == 0) {
        wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000 //持续的时间
        })
        this.homeIndex()
      } else {

      }
    })
  },
  // 放大背景图
  preview(event) {
    this.setData({
      imgList: []
    })
    this.data.personInfo.album.forEach(item => {
      this.data.imgList.push(item.pic.toString());
    });
    let currentUrl = event.currentTarget.dataset.src.pic
    wx.previewImage({
      current: currentUrl, // 当前显示图片的http链接
      urls: this.data.imgList // 需要预览的图片http链接列表
    })
  },
  aboutme() {
    this.setData({
      changeShow: false
    })
  },
  dongtai() {
    this.setData({
      changeShow: true
    })
  },
  //点赞
  giveTheThumbsup(event) {
    // console.log(event.currentTarget.dataset.user);
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let arys = {
      userId: app.globalData.user_id,
      recordId: event.currentTarget.dataset.user,
      time: timestamp,
      token: app.globalData.userToken,
    };
    let _token = axios.encryption(arys);
    let params = {
      userId: app.globalData.user_id,
      recordId: event.currentTarget.dataset.user,
      time: timestamp,
      token: app.globalData.userToken,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/record/likeRecord",
      data: params
    }).then((res) => {
      // console.log(res);
      if (res.data.status == 0) {
        wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000 //持续的时间
        })
        this.recordList()
      } else {

      }
    })
  },
  toroom() {
    wx.navigateTo({
      url: '/pages/room/room?roomId=' + this.data.personInfo.inRoomId,
    })
  },
  // 修改个人信息
  toModifyInformation(data) {
    console.log(JSON.stringify(data.currentTarget.dataset.index));
    wx.navigateTo({
      url: '/pages/means/means?index=' + JSON.stringify(data.currentTarget.dataset.index),
    })
  },

  // 去标签列表
  tosignlist(data) {
    console.log(data.currentTarget.dataset.signs_id);
    let arr = []
    data.currentTarget.dataset.signs_id.forEach((item) => {
      return arr.push(item.id)
    })
    console.log(arr);
    wx.navigateTo({
      url: '/pages/signlist/signlist?id=' + arr,
    })
  },
  followInsert_uesr(data) {
    let params = {
      followId: data.currentTarget.dataset.followid
    };
    axios.axios({
      url: "/user/followInsert",
      data: params
    }).then((res) => {
      wx.showToast({
        title: res.data.text,
        icon: 'none',
        duration: 2000
      })
    })
  },
  // 关注他
  payAttentionToHim(data) {
    let url;
    let isfow = data.currentTarget.dataset.isfow
    if (isfow == '0') {
      url = "/user/followInsert"
    } else {
      url = "/user/followCancel"
    }
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let arys = {
      userId: app.globalData.user_id,
      time: timestamp,
      followId: this.data.memberId,
      token: app.globalData.userToken,
    };
    let _token = axios.encryption(arys);
    let params = {
      followId: this.data.memberId,
      userId: app.globalData.user_id,
      time: timestamp,
      token: app.globalData.userToken,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: url,
      data: params
    }).then((res) => {
      console.log(res);
      if (res.data.status == 0) {
        wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000 //持续的时间
        })
        this.homeIndex()
      }
    })
  },
  tomessage() {
    wx.navigateTo({
      url: '/pages/withdraw/withdraw',
    })
  },
  copy() {
    // wx.setClipboardData({
    //   data: '' + this.data.personInfo.perfect_number,
    // })
  },
  //动态列表
  recordList() {
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let arys = {
      userId: app.globalData.user_id,
      type: "1",
      page: '0',
      findUserId: app.globalData.user_id,
      time: timestamp,
      token: app.globalData.userToken,
    };
    let _token = axios.encryption(arys);
    let params = {
      userId: app.globalData.user_id,
      type: "1",
      page: '0',
      findUserId: app.globalData.user_id,
      time: timestamp,
      token: app.globalData.userToken,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/record/recordList",
      data: params
    }).then((res) => {
      // console.log(res.data.result);
      if (res.data.status == 0) {
        // console.log(res.data.result.paicircleForms[0].isLiked);
        res.data.result.paicircleForms.forEach((item) => {
          let pic = item.picUrl.split(";")
          this.setData({
            pic: pic
          })
        })
        this.setData({
          recordList: res.data.result.paicircleForms
        })
      } else {
        wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000 //持续的时间
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  homeIndex() {
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let _token =
      "userId=" +
      app.globalData.user_id +
      "&token=" +
      app.globalData.userToken +
      "&time=" +
      timestamp +
      "&memberId=" +
      this.data.memberId +
      "&wPQvCAOU$lbIyg9o2wVg0Dt1k^zy&SaX";
    let params = {
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
      memberId: this.data.memberId,
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/index/homepage",
      data: params
    }).then((res) => {
      // console.log(res.data.result)
      if (res.data.result.userId == app.globalData.user_id) {
        this.setData({
          ismy_home: true
        })
      }
      this.setData({
        personInfo: res.data.result
      })
    })
  },
  fui_() {
    wx.navigateBack({ //返回
      delta: 1
    })
  },
  to_carAvtar(data) {
    let carAvatar = data.currentTarget.dataset.cardid
    let memberid = data.currentTarget.dataset.memberid
    console.log(data);
    wx.navigateTo({
      url: '/pages/carAvatar/carAvatar?carAvatar=' + carAvatar + '&memberid=' + memberid,
    })
  },
  to_medalWall(data) {
    let carAvatar = data.currentTarget.dataset.cardid
    let memberid = data.currentTarget.dataset.memberid
    wx.navigateTo({
      url: '/pages/medalWall/medalWall?medalWall=' + carAvatar + '&memberid=' + memberid,
    })
  },
  onLoad: function (options) {
    innerAudioContext.onEnded((res) => { //结束播放
      innerAudioContext.stop()
      this.setData({
        is_statys: false
      })
      console.log("结束的回调");
    })
    this.setData({
      memberId: options.memberId
    })
    this.homeIndex()
  },


  //显示对话框
  showModal: function () {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  //隐藏对话框
  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  },
  RecordingPopup() {
    this.setData({
      open_RecordingPopup: !this.data.open_RecordingPopup,
    })
    if (!this.data.open_RecordingPopup) {
      this.setData({
        Start_top: '点击下方录制按钮，开始录制声音',
        Start_bottom: '开始录音',
        tempFilePath: '',
        shiting: false,
        dianjiluzhi: true,
      })
      this.Reset(); //清空计时器
    }
  },
  start_time() {
    var that = this;
    clearInterval(that.data.init);
    that.setData({
      minute: 0,
      second: 0,
      millisecond: 0
    })
    that.data.init = setInterval(function () {
      that.timer()
    }, 50);
  },
  timer() {
    var that = this;
    that.setData({
      millisecond: that.data.millisecond + 5
    })
    if (that.data.millisecond >= 100) {
      that.setData({
        millisecond: 0,
        second: that.data.second + 1
      })
    }
    if (that.data.second >= 60) {
      that.setData({
        second: 0,
        minute: that.data.minute + 1
      })
    }
    if (that.data.minute >= 60) {
      that.setData({
        minute: 0,
      })
    }
    that.setData({
      timecount: that.data.minute + ":" + that.data.second + ":" + that.data.millisecond
    })
  },
  // 暂停
  stop_time() {
    clearInterval(this.data.init);
  },
  //开始录音的时候
  start_2: function () {
    this.start_time()
    this.setData({
      Start_top: '声音录制中，可以来段简短的自我介绍',
      Start_bottom: '录音中',
      dianjiluzhi: false,
      luzhizhong: true,
    })
    const options = {
      duration: 60000, //指定录音的时长，单位 ms
      sampleRate: 16000, //采样率
      numberOfChannels: 1, //录音通道数
      encodeBitRate: 96000, //编码码率
      format: 'mp3', //音频格式，有效值 aac/mp3
      frameSize: 50, //指定帧大小，单位 KB
    }
    //开始录音
    recorderManager.start(options);
    recorderManager.onStart(() => {
      console.log('recorder start')
    });
    //错误回调
    recorderManager.onError((res) => {
      console.log(res);

    })
  },

  //停止录音
  stop_2() {
    this.stop_time(),
      this.setData({
        Start_top: '录制完成，禁止上传任何反法律法规内容',
        Start_bottom: '点击试听',
        luzhizhong: false,
        shiting: true,
      })
    recorderManager.stop();
    recorderManager.onStop((res) => {
      console.log('停止录音', res.tempFilePath)
      this.setData({
        tempFilePath: res.tempFilePath
      })
    })
  },
  //播放声音
  shiting() {
    this.setData({
      shiting_2: false,
      bofang_zhanting: true,
      Start_bottom: '点击暂停',
    })
    innerAudioContext.autoplay = true
    innerAudioContext.src = this.data.tempFilePath,
      innerAudioContext.onPlay(() => {
        console.log('开始播放')
      })
    innerAudioContext.onPause((res) => { //暂停播放
      console.log('暂停播放回调!');
    })
    innerAudioContext.onEnded((res) => { //结束播放
      this.setData({
        shiting_2: true,
        bofang_zhanting: false,
        Start_bottom: '点击试听',
      })
      innerAudioContext.stop()
      console.log("结束的回调");
    })
    innerAudioContext.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
    })
  },
  // 暂停
  zanting_() {
    innerAudioContext.pause()
    this.setData({
      shiting_2: true,
      bofang_zhanting: false,
      Start_bottom: '点击继续',
    })
  },
  // 重录
  chong_recording() {
    this.setData({
      shiting: false,
      Start_top: '点击下方录制按钮，开始录制声音',
      Start_bottom: '开始录音',
      dianjiluzhi: true,
    })
    this.Reset(); //清空计时器
  },
  //确顶上传
  updata_andio() {
    console.log('点击确定');
    let that = this;
    wx.uploadFile({
      url: axios.testInterface + '/record/uploadVoice', //上传声音
      filePath: that.data.tempFilePath,
      voicefile: that.data.tempFilePath,
      name: "voicefile", //后台要绑定的名称
      //参数绑定
      formData: {
        'type': '1',
        'voicefile': that.data.tempFilePath,
        "userId": app.globalData.user_id,
        "token": app.globalData.userToken,
      },
      success: function (res) {
        var data = res.data
        const strToObj = JSON.parse(data)
        console.log("录音保存成功", strToObj);
        if (strToObj.status == '0') {
          wx.showToast({
            title: strToObj.text,
            icon: 'none',
            duration: 2000 //持续的时间
          })
          this.RecordingPopup()
        }
      },
      fail: function (res) {
        console.log("。。录音保存失败。。", res);
      }
    })
  },

  Reset() {
    var that = this;
    clearInterval(that.data.init);
    that.setData({
      minute: 0,
      second: 0,
      millisecond: 0,
      timecount: '00:00'
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // this.recordList()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
